
% function takes a pool of trajectories along with a table describing where
% the data comes from and calculates Delta D/D along with the baseline and
% standard deviation of baseline 

function [DDD,baselinemean,baselinestd,DDDz] = groupDDDcalculate(traj,infotable,baselineframes)


if nargin < 3 || isempty(baselineframes)
    baselineframes = 25:45;      %for 4.5s baseline
end
if max(strcmp('movieNumber',infotable.Properties.VariableNames))
    temp  = [infotable.movieNumber,infotable.globalVesselID,infotable.sessionNumber];
    [uid,~,idx] = unique(temp,'rows');          % this will have a unique ID for each vessel-loop combination - so this will be agnostic to the stimulus being presented which is fine because we're using this for baseline (i.e. before stimulus)
elseif max(strcmp('roi_stim_clusters',infotable.Properties.VariableNames))
    temp  = [infotable.uniqueVessels,infotable.roi_stim_clusters];
    [uid,~,idx] = unique(temp,'rows');          % this will have a unique ID for each vessel-loop combination - so this will be agnostic to the stimulus being presented which is fine because we're using this for baseline (i.e. before stimulus)
elseif max(strcmp('uniqueVessels',infotable.Properties.VariableNames))
    temp  = [infotable.uniqueVessels];
    [uid,~,idx] = unique(temp,'rows');          % this will have a unique ID for each vessel-loop combination - so this will be agnostic to the stimulus being presented which is fine because we're using this for baseline (i.e. before stimulus)
end
baselinemean = nan(size(traj,1),1);
baselinestd = nan(size(traj,1),1);
for n = 1:size(uid,1)
    curtraj = traj(idx == n,baselineframes);
    baselinemean(idx == n) = median(curtraj(:),'omitnan');
    baselinestd(idx == n) = std(curtraj(:),0,'omitnan');
end
DDDz = (traj - repmat(baselinemean,1,size(traj,2)))./repmat(baselinestd,1,size(traj,2));
DDD = (traj - repmat(baselinemean,1,size(traj,2)))./repmat(baselinemean,1,size(traj,2))*100;

